﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CommTestNFW.ImageCode
{
    public class PrintHelper
    {
        //public StreamReader PrintStream;
        //Font PrintFont;
        public List<string> ImagePaths = new List<string>();
        public int page = 0;
        public int pageCount = 0;

        public void Build(List<string> images)
        {
            ImagePaths = images;
            pageCount = ImagePaths.Count;
            //PrintStream = new StreamReader(docPath);

            PrintDocument pd = new PrintDocument();
            pd.DocumentName = "testR.pdf";

            //设置尺寸大小，如不设置默认是A4纸
            //A4纸的尺寸是210mm×297mm，
            //当你设定的分辨率是72像素/英寸时，A4纸的尺寸的图像的像素是595×842
            //当你设定的分辨率是150像素/英寸时，A4纸的尺寸的图像的像素是1240×1754
            //当你设定的分辨率是300像素/英寸时，A4纸的尺寸的图像的像素是2479×3508，
            //pd.DefaultPageSettings.PaperSize = new PaperSize("A4", 595, 842);
            pd.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);

            pd.BeginPrint += Pd_BeginPrint;
            pd.QueryPageSettings += Pd_QueryPageSettings;
            pd.PrintPage += new PrintPageEventHandler(Pd_PrintPage);
            pd.EndPrint += Pd_EndPrint;

            pd.Print();
        }

        private void Pd_BeginPrint(object sender, PrintEventArgs e)
        {
            Debug.WriteLine("打印开始");
            //处理打印前回调
        }

        private void Pd_EndPrint(object sender, PrintEventArgs e)
        {
            Debug.WriteLine("打印结束");
            //处理打印后回调
        }

        private void Pd_QueryPageSettings(object sender, QueryPageSettingsEventArgs e)
        {
            Debug.WriteLine($"即将打印第{page}页");
            //每页打印前处理



            //e.Cancel = true; //取消之后的所有打印
            //Debug.WriteLine($"取消打印第{page}页");
        }

        private void Pd_PrintPage(object sender, PrintPageEventArgs e)
        {
            Debug.WriteLine($"打印第{page}页...");
            if (page < pageCount)
            {
                var path = ImagePaths[page];
                Image image = new Bitmap(path);
                //设置整个文档大小为打印区域
                var rect = e.PageSettings.PrintableArea;
                e.Graphics.DrawImage(image, rect);
            }

            //如果打印还有下一页，将HasMorePages值置为true;
            e.HasMorePages = ++page < pageCount;
        }
    }
}
